import { app, BrowserWindow, Menu, ipcMain, shell } from 'electron'
import { exec } from 'child_process'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const isPackaged = app.isPackaged
const gotTheLock = app.requestSingleInstanceLock()

Menu.setApplicationMenu(null)

let mainWindow = null

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })

  const createWindow = () => {
    mainWindow = new BrowserWindow({
      title: '云网吧菜单',
      width: 1200,
      height: 700,
      resizable: false,
      frame: false,
      transparent: false,
      autoHideMenuBar: true,
      icon: join(__dirname, '../public/icons/png/256x256.png'),
      webPreferences: {
        preload: join(__dirname, './preload.js')
      }
    })

    process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

    if (!isPackaged) {
      mainWindow.webContents.openDevTools()
      mainWindow.loadURL('http://localhost:1420/')
    } else {
      mainWindow.webContents.openDevTools()
      mainWindow.loadURL('http://localhost:1420/')
      // if (process.platform === 'win32') {
      //   mainWindow.loadFile(join(app.getAppPath(), '../../../dist/index.html'))
      // } else {
      //   mainWindow.loadFile(join(app.getAppPath(), '../../../dist/index.html'))
      // }
    }
  }

  app.whenReady().then(() => {
    createWindow()
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })

  // 如果开发环境使用了 nginx 代理，禁止证书报错
  if (!isPackaged) {
    app.on('certificate-error', function (event, webContents, url, error, certificate, callback) {
      event.preventDefault()
      callback(true)
    })
  }
}

// 监听前端发送的消息
ipcMain.on('message', (event, message) => {
  if (message.type == 'openClient') {
    const openMoonlight = `//data//usershare//shengsuan//workspace//moonlight-embedded//build//moonlight ${message.params.token} ${message.params.content_id} ${message.params.signal_url}`
    const openTools = `${message.params.token}==${message.params.uid}==${message.params.hostIp}`
    console.log(openMoonlight)
    exec(openMoonlight, (error, a, b) => {
      if (!error) {
        console.error(`moonlight打开成功`)
      } else {
        console.error(`moonlight打开失败`)
      }
      console.log(a)
      console.log(b)
    })
    exec(openTools, (error) => {
      if (!error) {
        console.error(`悬浮球打开成功`)
      } else {
        console.error(`悬浮球打开失败`)
      }
    })
  } else if (message.type == 'openUrl') {
    shell.openExternal(message.params.url)
  } else if (message.type === 'miniWindow') {
    mainWindow.minimize()
  } else if (message.type === 'maxWindow') {
    mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize()
  } else if (message.type === 'closeWindow') {
    mainWindow.close()
    mainWindow = null
  }
})
